package com.heima.search.service.impl;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        //1.替换搜索关键词的所有特殊字符为空
        dto.setSearchWords(dto.getSearchWords().replaceAll("[^\u4e00-\u9fa5a-zA-Z0-9]", ""));

        //2.使用MongoDB的正则来查询联想词列表
        Query query = Query.query(Criteria.where("associateWords").regex(dto.getSearchWords()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        if(dto.getPageSize()<=0){
            dto.setPageSize(10);
        }
        query.limit(dto.getPageSize());
        List<ApAssociateWords> apAssociateWordsList = mongoTemplate.find(query, ApAssociateWords.class);

        return ResponseResult.okResult(apAssociateWordsList);
    }
}
